package com.lecoboy.redisdistributedlock;

import org.junit.Test;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;

public class RedisLockTest {

//    @Resource
//    private static Lock lock;

    private static int count = 10;

    public static void main(String[] args) throws InterruptedException {

        RedisLockThread rt = new RedisLockThread();
        Thread a = new Thread(rt, "【售票员A】");
        Thread b = new Thread(rt, "【售票员B】");
        Thread c = new Thread(rt, "【售票员C】");
        Thread d = new Thread(rt, "【售票员D】");
        a.start();
        b.start();
        c.start();
        d.start();
        Thread.currentThread().join();
    }

    @Test
    public void test() throws InterruptedException {

    }

    public static class RedisLockThread implements Runnable {

        @Override
        public void run() {
            final Lock lock = new RedisLockImpl();
            while (count > 0) {
                lock.lock();
                try {
                    if (count > 0) {
                        Thread.sleep(5000);
                        System.out.println(Thread.currentThread().getName() + "售出第:" + (count--) + "张票");
                    } else {
                        System.out.println(Thread.currentThread().getName() + "已经没有票了");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
}
